#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "funcutil.h"
#include "readconf.h"
#include "global.h"
#include "logger.h"

namespace wb
{

int daemon()
{
    switch (fork())
    {
    case -1:
        Logger::logger_core(LogLevel::Fatal, errno, "daemon() fork() failed");
        return -1;
    case 0:
        break; //fork成功，子进程跳出
    default:
        return 1; //父进程返回，可以准备清理资源退出了
    }

    ppid = pid;
    pid = getpid(); //重新获得进程ID
    
    if (setsid() == -1)
    {
        Logger::logger_core(LogLevel::Fatal, errno, "daemon() setsid() failed");
        return -1;
    }

    umask(0);
    
    int fd = open("/dev/null", O_RDWR);
    if (fd == -1)
    {
        Logger::logger_core(LogLevel::Fatal, errno, "daemon() open(/dev/null) failed");
    }
    if (dup2(fd, STDIN_FILENO) == -1)
    {
        Logger::logger_core(LogLevel::Fatal, errno, "daemon() dup2(stdin) failed");

    }
    if (dup2(fd, STDOUT_FILENO) == -1)
    {

        Logger::logger_core(LogLevel::Fatal, errno, "daemon() dup2(stdout) failed");
    }
    if (fd > STDERR_FILENO)
    {
        if (close(fd) == -1)
        {
            Logger::logger_core(LogLevel::Fatal, errno, "daemon() close(fd[3]) failed");
        }
    }

    return 0;

}




    
}